package net.xby1993.lockscreen;

import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;


public class MainActivity extends Activity {

    private DevicePolicyManager pm;
    private static int MY_REQUEST_CODE=999;
    private ComponentName componentName;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pm =(DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
        componentName=new ComponentName(this,MyAdminReceiver.class);

       //检测是否拥有设备管理权限
        if(pm.isAdminActive(componentName)){
            pm.lockNow();
            finish();
        }else{
            activeManager();
        }
        //放在最后
        setContentView(R.layout.activity_main);
    }

    private void activeManager(){
        Intent intent=new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,componentName);
        intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,R.string.hint);
        startActivityForResult(intent,MY_REQUEST_CODE);
    }
    @Override
    protected void onActivityResult(int reqCode,int resCode,Intent data){
        if(reqCode==MY_REQUEST_CODE&&resCode== Activity.RESULT_OK){
            pm.lockNow();
            finish();
        }else{
            activeManager();
        }
        super.onActivityResult(reqCode,resCode,data);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }


}
